package com.benchmark.springboot.controller;

import com.benchmark.springboot.model.NetInterfaceAndIpInfo;
import com.power.common.model.CommonResult;
import com.power.common.util.IpUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.InetAddress;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 获取ip地址
 *
 * @author yu 2019/4/24.
 */
@RestController
@RequestMapping("ip")
public class IpController {

    /**
     * 获取本机ip地址
     *
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/")
    public CommonResult<String> getIp() throws Exception {
        InetAddress addr = InetAddress.getLocalHost();
        String ip = addr.getHostAddress();
        return CommonResult.ok().setResult(ip);
    }

    /**
     * 获取所有的ipv4地址
     *
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/v4/all")
    public CommonResult<List<NetInterfaceAndIpInfo>> getIPV4All() {
        Map<String, String> ipAddress = IpUtil.getLocalIPV4();
        //此步骤只是为了方便看描述信息，实际可直接方为map信息
        List<NetInterfaceAndIpInfo> list = convertMapToList(ipAddress);
        return CommonResult.ok().setResult(list);
    }

    /**
     * 根据网卡获取ipv4地址
     *
     * @param netInterface 网卡名称(eth0,ens33等)|eth0
     * @return
     */
    @GetMapping(value = "/v4/{netInterface}")
    public CommonResult<String> getIPV4ByInterface(@PathVariable String netInterface) {
        String ip = IpUtil.getLocalIPV4().get(netInterface);
        return CommonResult.ok().setResult(ip);
    }

    /**
     * 获取所有的ipv6地址
     *
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/v6/all")
    public CommonResult<List<NetInterfaceAndIpInfo>> getIPV6All() {
        Map<String, String> ipAddress = IpUtil.getLocalIPV6();
        List<NetInterfaceAndIpInfo> list = convertMapToList(ipAddress);
        return CommonResult.ok().setResult(list);
    }


    /**
     * 根据网卡获取ipv6地址
     *
     * @param netInterface 网卡名称(eth0,ens33等)|eth0
     * @return
     */
    @GetMapping(value = "/v6/{netInterface}")
    public CommonResult<String> getIPV6ByInterface(@PathVariable String netInterface) {
        String ip = IpUtil.getLocalIPV6().get(netInterface);
        return CommonResult.ok().setResult(ip);
    }


    private List<NetInterfaceAndIpInfo> convertMapToList(Map<String, String> ipAddress) {
        List<NetInterfaceAndIpInfo> list = ipAddress.entrySet().stream()
                .map(e -> new NetInterfaceAndIpInfo().setNetInterface(e.getKey()).setIp(e.getValue()))
                .collect(Collectors.toList());
        return list;
    }
}
